package com.android.manghe.market.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;

import androidx.core.app.ActivityCompat;

import com.alipay.sdk.app.PayTask;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.okhttp.okUtil.callback.GsonBaseBack;
import com.android.base.tools.ToastUtil;
import com.android.base.tools.codec.MD5;
import com.android.manghe.box.model.BoxPrizeModel;
import com.android.manghe.box.model.PayWayModel;
import com.android.manghe.cache.PayHolder;
import com.android.manghe.cache.StatusHolder;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.AliPayRes;
import com.android.manghe.common.model.BaseBack;
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.model.WXPayRes;
import com.android.manghe.common.model.WechatConfig;
import com.android.manghe.common.model.YiZhiFuRes;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.market.activity.BoxDetailActivity;
import com.android.manghe.market.model.BoxCheckOrderModel;
import com.android.manghe.market.model.BoxSubmitModel;
import com.android.manghe.mine.model.SandPayH5Model;
import com.android.manghe.mine.model.SandPayModel;
import com.android.manghe.tuia.TuiAManager;
import com.android.manghe.utils.ApiCrypter;
import com.android.manghe.utils.PayResult;
import com.bestpay.app.PaymentTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.jetbrains.annotations.NotNull;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/10/25 15:28
 * desc   :
 */
public class PBoxDetail extends XPresenter<BoxDetailActivity> {


    private int currentPage = 1;
    private final String PageSize = "10";
    private final List<BoxPrizeModel.DataBean.ListBean> boxPrizeList = new ArrayList<>();
    private String manghe_id;

    private String out_trade_no=null;

    public String getOut_trade_no() {
        return out_trade_no;
    }

    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }

    public void setManghe_id(String manghe_id) {
        this.manghe_id = manghe_id;
    }

    public void getBoxPrizeList(boolean isRefresh) {
        //获取开盒纪录
        if (isRefresh) {
            currentPage = 1;
            boxPrizeList.clear();
        }
        HashMap<String, String> data = new HashMap<>();
        data.put("page", currentPage + "");
        data.put("size", PageSize);
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.Box_Prize_List, data)
                .get()
                .execute(new BaseBack<BoxPrizeModel>() {
                    @Override
                    public void onSuccess(Call call, BoxPrizeModel res) {
                        getV().hideLoadingDialog();
                        if (res != null && res.code == 0) {
                            if (res.data.list != null) {
                                boxPrizeList.addAll(res.data.list);
                                getV().setCanLoadMore(boxPrizeList.size() != res.data.list_total);
                                getV().updateList(boxPrizeList);
                                if (boxPrizeList.size() != res.data.list_total) {
                                    currentPage++;
                                }

                            } else {
                                getV().setCanLoadMore(false);
                                getV().updateList(boxPrizeList);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                    }

                });

    }

    public void getBoxPrize() {
        //获取中奖的消息
        HashMap<String, String> data = new HashMap<>();
        data.put("page", "1");
        data.put("size", "100");
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.Box_Prize_List, data)
                .get()
                .execute(new BaseBack<BoxPrizeModel>() {

                    @Override
                    public void onSuccess(Call call, BoxPrizeModel res) {
                        if (res != null && res.data != null) {
                            getV().updatePrize(res.data.list);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void getPaymentType(BoxCheckOrderModel.DataBean dateBean, View v) {
        HashMap<String, String> data = new HashMap<>();
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.FLOWPAYMENT, data)
                .get()
                .execute(new BaseBack<PaymentTypeRes>() {

                    @Override
                    public void onSuccess(Call call, PaymentTypeRes res) {
                        getV().hideLoadingDialog();
                        if (res != null && res.data != null && res.data.payment != null && res.data.payment.size() != 0) {
                            getV().updatePayments(res.data.payment, dateBean, v);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }


    /**
     * 检查盲盒订单
     *
     * @param manghe_id
     * @param num
     * @param view
     */
    public void getBoxCheckOrder(String manghe_id, int num, View view) {
        HashMap<String, String> data = new HashMap<>();
        data.put("id", manghe_id);
        data.put("num", num + "");
        data.put("use_score", 1 + "");
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
        headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Check_Order, headMap)
                .post(data).build()
                .execute(new BaseBack<BoxCheckOrderModel>() {

                    @Override
                    public void onSuccess(Call call, BoxCheckOrderModel res) {
                        if (res != null && res.data != null) {
                            getV().updateCheckOrder(res.data, view);
                        } else {
                            getV().showCheckTip();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                        getV().showCheckTip();
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }


    /**
     * 检测盲盒订单的余额是否足够
     *
     * @param manghe_id
     * @param num
     * @param pay_id
     */
    public void getBoxSubmitOrder(String manghe_id, int num, String pay_id, String payCode,int use_score) {
        getV().showLoadingDialog();
        HashMap<String, String> data = new HashMap<>();
        data.put("id", manghe_id);
        data.put("num", num + "");
        data.put("pay_id", pay_id);
        data.put("use_score",use_score+"");
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
        headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Check_YU_ER, headMap)
                .post(data).build()
                .execute(new BaseBack<BoxSubmitModel>() {

                    @Override
                    public void onSuccess(Call call, BoxSubmitModel res) {
                        getV().hideLoadingDialog();
                        if (res != null && res.data != null) {
                            getV().updateSubmitModel(res.data, pay_id, payCode, num);
                        } else {
                            getV().showSubmitTip();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().showSubmitTip();
                        getV().hideLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }


    /**
     * 提交盲盒订单
     *
     * @param order_id
     * @param payCode
     */
    public void getOrderMsg(String order_id, String pay_id, String payCode) {
        getV().showLoadingDialog();
        StatusHolder.mCurrentPayType = 0;
        HashMap<String, String> data = new HashMap<>();
        data.put("order_id", order_id);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
        headMap.put("PLATFORM", "android");
        if (payCode.equals("shangmeng")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<BuyMemberShangMengZhiFuRes>() {
                        @Override
                        public void onSuccess(Call call, BuyMemberShangMengZhiFuRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null) {
                                PayHolder.shangMengCouponId = order_id;
                                PayHolder.shangMengPayid = pay_id;
                                getV().openQuickPay(res.data);
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });

        } else if (payCode.equals("sandpay")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<SandPayModel>() {
                        @Override
                        public void onSuccess(Call call, SandPayModel res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                getV().cashierPay(res.data);
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        } else if (payCode.equals("sandpayh5")) {
            //杉德H5支付
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<SandPayH5Model>() {
                        @Override
                        public void onSuccess(Call call, SandPayH5Model res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null&&res.data.paycode!=null) {
                                getV().cashierPayH5(res.data);
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });


        } else if (payCode.equals("alipayapp")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<AliPayRes>() {
                        @Override
                        public void onSuccess(Call call, AliPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                toPayByAli(res.data.paycode);
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        } else if (payCode.equals("yizfpay")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<YiZhiFuRes>() {
                        @Override
                        public void onSuccess(Call call, YiZhiFuRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                toPayYiZhiFu(new GsonBuilder().disableHtmlEscaping().create().toJson(res.data.paycode));
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        } else if (payCode.equals("wxpayapp") || payCode.equals("wxpayapp2")) {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<WXPayRes>() {

                        @Override
                        public void onSuccess(Call call, WXPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null && res.data.paycode.appid != null) {
                                new OKHttpUtil(getV()).url(ConstantsUrl.domain + (payCode.equals("wxpayapp") ? ConstantsUrl.WX_CONFIG : ConstantsUrl.WX_CONFIG2))
                                        .get()
                                        .execute(new GsonBaseBack() {
                                            @Override
                                            public void onSuccess(Call call, String json) {
                                                getV().hideLoadingDialog();
                                                NetBean<String> netBean = new Gson().fromJson(json, NetBean.class);
                                                if (netBean != null && netBean.code == 0 && !TextUtils.isEmpty(netBean.data)) {
                                                    try {
                                                        String dataString = URLDecoder.decode(new String(new ApiCrypter().decrypt(netBean.data), "UTF-8"), "UTF-8");
                                                        if (!TextUtils.isEmpty(dataString)) {
                                                            WechatConfig config = new Gson().fromJson(dataString, WechatConfig.class);
                                                            if (config != null) {
                                                                if (!TextUtils.isEmpty(config.wxpay_app_id)) {
                                                                    ConstantsUrl.PAY_WX_APPID = config.wxpay_app_id;
                                                                }
                                                                toPayByWx(res.data.paycode);
                                                            } else {
                                                                getV().payFail();
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                        getV().payFail();
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onFailure(Exception e) {
                                                super.onFailure(e);
                                                getV().hideLoadingDialog();
                                                getV().payFail();
                                            }

                                            @Override
                                            public void onComplete() {
                                                getV().hideLoadingDialog();
                                            }
                                        });
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        } else {
            new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Submit_Order, headMap)
                    .post(data).build()
                    .execute(new BaseBack<AliPayRes>() {

                        @Override
                        public void onSuccess(Call call, AliPayRes res) {
                            getV().hideLoadingDialog();
                            if (res != null && res.data != null && res.data.paycode != null) {
                                if (payCode.equals("yipayweixinh5")) {
                                    //微信H5，打开手机浏览器
                                    getV().toPayByBrowser(res.data.paycode, res.data.order.log_id);
                                } else {
                                    //其他就打开浏览器支付。例如盛付通
                                    getV().toPayByH5(res.data.paycode);
                                }
                            } else {
                                getV().payFail();
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            super.onFailure(e);
                            getV().hideLoadingDialog();
                            getV().payFail();
                        }

                        @Override
                        public void onComplete() {
                            getV().hideLoadingDialog();
                        }
                    });
        }
    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(@NotNull Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        ToastUtil.showShort(getV(), "支付成功");
                        getV().paySuccess();
                        TelephonyManager tm = (TelephonyManager) getV().getSystemService(Service.TELEPHONY_SERVICE);
                        if (ActivityCompat.checkSelfPermission(getV(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        TuiAManager.send(getV(), MD5.md5(tm.getDeviceId()), 6);
                        //OpenInstall.reportEffectPoint(Config.OpenInstall_Voucher, MoneyUtil.changeY2F(getV().getMCurrentPrice()));

                        Map<String, String> map_value = new HashMap<>();
                        map_value.put("charge", "1");
                        //MobclickAgent.onEventValue(getV(), "charge", map_value, MoneyUtil.changeY2F(getV().getMCurrentPrice()));

                        //PayTrack
                        try {
                            Map successPayMap = new HashMap();
                            successPayMap.put("userid", UserHolder.getUID(getV()));
                            successPayMap.put("orderid", System.currentTimeMillis());
                            successPayMap.put("item", "购券");
                            //successPayMap.put("amount", MoneyUtil.changeY2F(getV().getMCurrentPrice()));
                            MobclickAgent.onEvent(getV(), "__finish_payment", successPayMap);
                        } catch (Exception e) {
                        }

                        //getV().paySuccess();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ToastUtil.showShort(getV(), "支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtil.showShort(getV(), "支付取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtil.showShort(getV(), "网络异常");
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            ToastUtil.showShort(getV(), "重复请求");
                        } else {
                            // 其他值就可以判断为支付失败
                            ToastUtil.showShort(getV(), "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void toPayByAli(String orderInfo) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getV());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void toPayByWx(WXPayRes.DataBean.PaycodeBean bean) {
        // StatusHolder.mCurrentVoucherPrice = getV().getMCurrentPrice();
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(getV(), ConstantsUrl.PAY_WX_APPID, true);
        iwxapi.registerApp(ConstantsUrl.PAY_WX_APPID);
        PayReq req = new PayReq();
        req.appId = ConstantsUrl.PAY_WX_APPID;
        req.partnerId = bean.partnerid;
        req.prepayId = bean.prepayid;
        req.packageValue = bean.wxpackage;
        req.nonceStr = bean.noncestr;
        req.timeStamp = bean.timestamp + "";
        req.sign = bean.sign;
        iwxapi.sendReq(req);
    }

    private void toPayYiZhiFu(String payString) {
        payString = payString.replace("{\"", "").replace("\"}", "")
                .replace("\":\"", "=").replace("\",\"", "&");//.replace("+","%2B")
        PaymentTask paymentTask = new PaymentTask(getV());
        paymentTask.pay(payString, ConstantsUrl.YiZhiFuLicense);

    }


    public void getPayWay() {
        HashMap<String, String> data = new HashMap<>();
        data.put("out_trade_no", out_trade_no);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
        headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_GET_PAY_WAY, data, headMap)
                .get()
                .execute(new BaseBack<PayWayModel>() {
                    @Override
                    public void onSuccess(Call call, PayWayModel res) {
                        getV().hideLoadingDialog();
                        if (res != null && res.code == 0 && res.data != null) {
                            getV().showPayWay(res.data);
                        } else {
                            getV().payFail();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                        getV().payFail();
                    }

                });
    }

}
